package org.rslai.util.email;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.Session;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

/**
 * 使用imap协议获取未读邮件数
 * @author rslai
 */
public class IMAP {

	public boolean receiveAll(IMAPinfo imapInfo) throws Exception {
		String user = imapInfo.getUserName();// 邮箱的用户名
		String password = imapInfo.getPassword(); // 邮箱的密码

		Session session = Session.getInstance(imapInfo.getProperties());

		IMAPStore store = (IMAPStore) session.getStore(imapInfo.getProtocol()); // 使用imap会话机制，连接服务器
		store.connect(user, password);
		IMAPFolder folder = (IMAPFolder) store.getFolder(imapInfo.getFolder()); // 收件箱
		folder.open(imapInfo.getFolderReadWriteMode());
		// 获取总邮件数
		int total = 0;
		total = folder.getMessageCount();
		System.out.println("TotalMessageCount：" + total);
		// 得到收件箱文件夹信息，获取邮件列表
		System.out.println("UnreadMessageCount：" + folder.getUnreadMessageCount());
		System.out.println();
		Message[] messages = folder.getMessages();
		int messageNumber = 0;
		for (Message message : messages) {
			Flags flags = message.getFlags();
			if (flags.contains(Flags.Flag.SEEN))
				System.out.println("Flag：已读");
			else {
				System.out.println("Flag：未读");
			}
			System.out.println("SentDate：" + message.getSentDate());
			System.out.println("Subject：" + message.getSubject());
			System.out.println("ContentType：" + message.getContentType());
//			System.out.println("Content：" + message.getContent()); 暂时注释，运行读取gbk错误
			System.out.println();

			// 每封邮件都有一个MessageNumber，可以通过邮件的MessageNumber在收件箱里面取得该邮件
			messageNumber = message.getMessageNumber();
		}
		// 根据MessageNumber直接读出一封邮件
		Message message = folder.getMessage(messageNumber);
		System.out.println(message.getContent() + message.getContentType());

		// 释放资源
		if (folder != null)
			folder.close(true);
		if (store != null)
			store.close();

		return true;
	}

}
